<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Realtime_item extends MY_Controller {

	function Realtime_item() {
		parent::__construct();
		$this->load->model('realtime_item_model');
		$this->load->model('realtime_data_model');
	}

	public function index() {
		$realtime_items = $this->realtime_item_model->get_item_list();
		if($this->session->userdata('logged_in') && $this->session->userdata('role_id') == 1){
			$this->load->view('realtime_item', array('realtime_items' => $realtime_items));
		} else {
			$this->load->view('login');
		}
	} 

	public function add() {
		$item_name    = $this->input->post('item_name');
		$item_key    = $this->input->post('item_key');
		$safe_value     = $this->input->post('safe_value');
		$alarm_value    = $this->input->post('alarm_value');
		$item_type    = $this->input->post('item_type');
		$item_server  = $this->input->post('item_server');
		$alarm_content   = $this->input->post('alarm_content');
		$item_keys= $this->realtime_item_model->get_by_item_key($item_key);
		if (empty($item_keys)) {
			$this->realtime_item_model->add($item_name, $item_key, $safe_value, $alarm_value, $item_type, $item_server, $alarm_content);
		} else {
			echo "<script>alert('Already exist');window.history.go(-1);</script>";
		}
		redirect("/realtime_item");
	}

	public function delete() {
		$item_id  = $this->input->get('item_id');
		$item_ids = $this->realtime_item_model->get_by_id($item_id);
	    if (!empty($item_ids)) {
	    	$this->realtime_item_model->delete($item_id);
	    } else {
	    	echo "<script>alert('Not exist');window.history.go(-1);</script>";
	    }
	    redirect("/realtime_item");
	}

	public function update() {
		$item_id    = $this->input->post('item_id');
		$item_name  = $this->input->post('item_name');
		$item_key   = $this->input->post('item_key');
		$safe_value  = $this->input->post('safe_value');
		$alarm_value  = $this->input->post('alarm_value');
		$item_type= $this->input->post('item_type');
		$item_server = $this->input->post('item_server');
		$alarm_content   = $this->input->post('alarm_content');
		$this->realtime_item_model->update($item_id, $item_name, $item_key, $safe_value, $alarm_value, $item_type, $item_server, $alarm_content);
		redirect("/realtime_item");
	}

	public function return_id_and_server() { 
		$item_id = $this->input->post('item_id');
		$item_server = $this->input->post('item_server');
		echo json_encode(["item_id"=>$item_id,"item_server"=>$item_server]);
	}

	public function get_first_id_and_server() { 
		$realtime_servers = $this->realtime_item_model->get_server_list();
		$realtime_item_names = $this->realtime_item_model->get_all_item_name();
		echo json_encode(["item_id" =>$realtime_item_names[0]['item_id'],"item_server" =>$realtime_servers[0]['item_server']]);
	}
	
}